//
//  WQOAuthViewController.swift
//  WeiBo
//
//  Created by Xmen on 16/9/20.
//  Copyright © 2016年 111. All rights reserved.
//

import UIKit
import SVProgressHUD

let wbAppKey: String = "4139824546"
let wbRedirect_Uri: String = "http://www.itcast.cn"
let wbAppSecret = "a5bd7309f064bfa8e7cf50194562cc03"

class WQOAuthViewController: UIViewController {

    // 懒加载一个webView视图
    private lazy var webView: UIWebView = UIWebView()
    // 重写loadView将webView作为vc的视图
    override func loadView() {
        view = webView
        webView.isOpaque = false
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestLogin()
        setupNavUI()
    }


    func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cencleAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autofillAction))
        title = "微博"
    }
    
    @objc private func cencleAction(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autofillAction(){

        print("js")
    }
    
    // 第三方登录
    private func requestLogin() {
        //  准备url地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(wbAppKey)&redirect_uri=\(wbRedirect_Uri)"
        //  创建urlrequest对象
        let urlRequest = URLRequest(url: URL(string: url)!)
        webView.loadRequest(urlRequest)
    }

}


extension WQOAuthViewController: UIWebViewDelegate{
    //  开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.url else {
            print("url 为 nil")
            return false
        }
        
        if !url.absoluteString.hasPrefix(wbRedirect_Uri){
            return true
        }
        if let query = url.query,query.hasPrefix("code="){
            let code = query.substring(from: "code=".endIndex)
            
            WQUserAccountModel.sharedUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    //  表示登录成功
                    print("登录成功")
                    //  要等到dismis完成以后在发送切换根视图控制器的操作
                    self.dismiss(animated: false, completion: {
                        //  进入欢迎页面
                        
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                    
                }
                    })

        } else {
            // 取消授权
            dismiss(animated: true, completion: nil)
        }
                return false
    }
    
    
    
    
}





